from tkinter import messagebox, ttk
import tkinter as tk
import json
import os

def sign_in(root, user, password):
    '''
    验证用户输入的用户名和密码
    验证成功后结束登录窗口并进入主界面
    否则提示错误
    '''
    if not os.path.exists("user.json"):
        messagebox.showerror( "错误", "请先注册用户")
        return
    user_val, password_val = user.get(), password.get()
    with open("user.json", "r") as f:
        users = json.load(f)
        boss_password = users["boss"]
        admin_password = users["admin"]
    if (user_val == "部门领导" and password_val in boss_password) or \
        (user_val == "仓库管理员" and password_val in admin_password):
        messagebox.showinfo("成功", "登录成功！")
        root.destroy()
        from main import main
        main(user_val)
    else:
        messagebox.showerror("错误", "密码错误! 请重新输入")

def register_user(user, password):
    '''
    为管理员或部门领导注册新用户
    将用户名和密码写入user.json文件
    '''
    user_val = user.get()
    password_val = password.get()
    
    if not user_val or not password_val:
        messagebox.showerror("错误", "用户名或密码不能为空")
        return False
    
    if os.path.exists("user.json"):
        with open("user.json", "r") as f:
            users = json.load(f)
    else:
        # 创建新的用户数据结构
        users = {"boss": [], "admin": []}
    
    if user_val == "部门领导":
        users["boss"].append(password_val)
    elif user_val == "仓库管理员":
        users["admin"].append(password_val)
        
    with open("user.json", "w") as f:
        json.dump(users, f)
    messagebox.showinfo("成功", "注册成功!")
    return True

def sign_up():
    '''
    创建新窗口
    用于注册新用户
    '''
    window = tk.Toplevel()  # 使用Toplevel而不是Tk，这样它会成为主窗口的子窗口
    window.title("注册")
    window.resizable(False, False)
    width = 300
    height = 180
    screenwidth = window.winfo_screenwidth()
    screenheight = window.winfo_screenheight()
    window.geometry('%dx%d+%d+%d'%(width, height, (screenwidth-width)/2, (screenheight-height)/2))
    window.grab_set()  # 使窗口成为模态窗口，强制用户先处理这个窗口

    ttk.Label(window, text="请在下方进行注册").pack(pady=10)
    User_Frame = ttk.Frame(window)
    ttk.Label(User_Frame, text="请选择用户:").grid(row=0, column=0)
    user = tk.StringVar()
    com = ttk.Combobox(User_Frame, textvariable=user)
    com['values'] = ("部门领导", "仓库管理员")
    com.current(1)
    com.grid(row=0, column=1)
    User_Frame.pack(pady=10)

    Password_Frame = ttk.Frame(window)
    ttk.Label(Password_Frame, text="密码:").grid(row=0, column=0)
    password = tk.StringVar()
    ttk.Entry(Password_Frame, textvariable=password, show='*').grid(row=0, column=1, ipadx=10)
    Password_Frame.pack(pady=10)

    # 定义一个内部函数来处理注册并关闭窗口
    def register_and_close():
        if register_user(user, password):
            window.destroy()

    Button_Frame = ttk.Frame(window)
    ttk.Button(Button_Frame, text="注册", command=register_and_close).grid(row=0, column=0)
    ttk.Button(Button_Frame, text="返回", command=window.destroy).grid(row=0, column=1)
    Button_Frame.pack(pady=10)
    window.mainloop()

def login():
    root = tk.Tk()
    root.title("登录")
    root.resizable(False, False)
    width = 300
    height = 180
    screenwidth = root.winfo_screenwidth()
    screenheight = root.winfo_screenheight()
    root.geometry('%dx%d+%d+%d'%(width, height, (screenwidth-width)/2, (screenheight-height)/2))

    ttk.Label(root, text="欢迎使用仓库管理系统").pack(pady=10)

    User_Frame = ttk.Frame(root)
    ttk.Label(User_Frame, text="请选择用户:").grid(row=0, column=0)
    user = tk.StringVar()
    com = ttk.Combobox(User_Frame, textvariable=user)
    com['values'] = ("部门领导", "仓库管理员")
    com.current(1)
    com.grid(row=0, column=1)
    User_Frame.pack(pady=10)

    Password_Frame = ttk.Frame(root)
    ttk.Label(Password_Frame, text="请输入密码:").grid(row=0, column=0)
    password = tk.StringVar()
    ttk.Entry(Password_Frame, textvariable=password, show='*').grid(row=0, column=1, ipadx=10)
    Password_Frame.pack(pady=10)

    Button_Frame = ttk.Frame(root)
    ttk.Button(Button_Frame, text="登录", command=lambda: sign_in(root,  user, password)).grid(row=0, column=0)
    ttk.Button(Button_Frame, text="注册", command=lambda: sign_up()).grid(row=0, column=1)
    Button_Frame.pack(pady=10)
    
    root.mainloop()